$(document).ready(function() {	
	getHeatMapLists(1);
	function getParamer(){
		var data = [];
		var newsTitle = {};
		newsTitle["property"] = "heatMapTitle";
		newsTitle["value"] = $("#heatMapTitle").val();
		newsTitle["condition"] = "fl";
		if(isNotBlank($("#heatMapTitle").val())){
			data[0] = newsTitle;
		}
		
		var newsStatus = {};	
		newsStatus["property"] = "heatMapStatus";
		newsStatus["value"] = $("#heatMapStatus").val();	
		newsStatus["condition"] = "eq";
		if(isNotBlank($("#heatMapStatus").val())){
				data[data.length] = newsStatus;		
		}
		
		var languageId = {};
		languageId["property"] = "languageId";
		languageId["value"] = $("#languageId").val();
		languageId["condition"] = "eq";
		if(isNotBlank($("#languageId").val())){
			data[data.length] = languageId;
		}
		
		return $.toJSON(data);
	}
	$(".form-layout .button").click(function(){
		//var dataArray = $("form").serializeArray();		
		getHeatMapLists(1, null, null, getParamer());
	})
	function getHeatMapLists(pageNo, orderType, orderBy, paramdata){	
			if(!pageNo){
				pageNo = 1;
			}
			if(!orderType){
				orderType = "desc";
			}
			if(!orderBy){
				orderBy = "heatMapStatus";
			}
			if(!paramdata){
				paramdata="[]";
			}	
			pagination({
				url:ctx+"/home/heatMap/search.do",
				data:{
					pageNo:pageNo,
					pageSize : 5,
					orderType : orderType, 
					orderBy : orderBy, 
					rules : paramdata
				},
				callback: function(data){
					generateHeatMapLists(data);
					paginationClick();
				}
			})
		}
	 function generateHeatMapLists(data){
		var tbody = $("tbody", "#descform").empty();
		if(data.result.length == 0){
			$(".submit").hide();
			return;
		}
		$(".submit").show();
		$.each(data.result, function(i, bean){
				var tr = $("<tr>").appendTo(tbody);
				$("<td class='td_0_'>").text(i+1).appendTo(tr);
				$("<td>").append($("<input type='checkbox'>").attr("name", "heatMap['"+i+"'].heatMapStatus").val(bean.heatMapStatus).attr("checked",bean.heatMapStatus)).appendTo(tr);
				$("<td>").text(bean.heatMapTitle).appendTo(tr);
			
				var fileInfoId = bean.fileInfoId?bean.fileInfoId:bean.uploadFileInfoId;
				var img = $("<img>").attr("src", ctx+ "/home/imagesrc2.do?width=200&height=150&fileInfoId="+fileInfoId);
				var images = $("<div class='images'>").append(img);
				$("<td>").append(images).appendTo(tr);
				
				$("<td class='boxcaption'>").append(
				$("<textarea>").attr("name", "heatMap['"+i+"'].heatMapDesc").text(bean.heatMapDesc)).append(
												
				$("<input type=\"hidden\">").addClass("hidden-heatMapId").attr("name", "heatMap['"+i+"'].heatMapId").val(bean.heatMapId)).append(
				$("<input type=\"hidden\">").attr("name", "heatMap['"+i+"'].linkedHeatMapId").val(bean.linkedHeatMapId))
				.appendTo(tr);
				//$("<td class='td-5'>").append($("<input class='uploadify-button' type='button' value='刪除'>")).appendTo(tr);
				//$("<td class='td-6'>").append($("<input class='uploadify-button' type='button' value='主頁顯示'>")).appendTo(tr);
				//$("<td class='td-7'>").append($("<input type='file'>").attr("id", "file-"+bean.uploadFileInfoId)).appendTo(tr);
				$("<td class='td-5'>")
				//.append($("<input class='uploadify-button' type='button' value='刪除'>"))
				//.append($("<input class='uploadify-button' type='button' value='主頁顯示'>"))
				.append($("<input type=\"hidden\">").addClass("hidden-uploadFileInfo").attr("name", "heatMap['"+i+"'].uploadFileInfoId").val(bean.uploadFileInfoId)
				).append($("<input type=\"hidden\">").addClass("hidden-fileInfo").attr("name", "heatMap['"+i+"'].fileInfoId").val(bean.fileInfoId)
				.data("data-fileName", bean.fileName)
				).append($("<input type='file'>").attr("id", "file-"+fileInfoId)).appendTo(tr);	
		})
		bindCheckbox();
		bindUploadify();
		generateFileInfo();
		// Check all checkboxes when the one in a table head is checked:
		$('.check-all').attr("checked", true);
		var allChecked = $("#datatable tbody tr").find(":checkbox").each(function(){
			if(!$(this).is(':checked')){
				$('.check-all').attr("checked", false);
			}
		})
		$('.check-all').click(function(){
			$("#datatable tbody tr").find("input[type='checkbox']").attr('checked', $(this).is(':checked')).val($(this).is(':checked'));   
		});
		//$(".tablesorter").tablesorter({textExtraction: statusExtraction, sortList: [[0,1]]} );
	}
	function statusExtraction(node){
		if($(node).find(":checkbox").length >0)
		return $(node).find(":checkbox").val();
		else
		return $(node).text();
	}
	function deleteHotPic(file_id, uploadFileInfoId, flag){
		if(flag){
			var uploadfyId = $("#"+file_id).parents("td").find(".uploadify").attr("id");
			var uploadLimit = $('#'+uploadfyId).data("uploadify").settings.uploadLimit;
			$('#'+uploadfyId).uploadify('settings','uploadLimit', uploadLimit+1);
		}
		$.ajax({
			url: ctx+"/home/deleteUploadFile.do",
			type: "post",
			data:{uploadFileInfoId : uploadFileInfoId},
			success: function(d){
				var sourceFile = $("#"+file_id).parents("td").find(".hidden-uploadFileInfo");				
				$("#"+file_id).parents("td").find(".hidden-fileInfo").val("");
				var img = $("#"+file_id).parents("tr").find("img");
				var src = img.attr("src");
				var f = src.lastIndexOf("=");
				src = src.substring(0, f);
				img.attr("src", src+"="+sourceFile.val());
			},
			error: function(e){
				
			}
		})
	}
	function deleteHeatMapFileInfo(heatMapId){
		$.ajax({
			url: ctx+"/home/heatMap/deleteHeatMapFileInfo.do",
			type: "post",
			data:{heatMapId : heatMapId},
			success: function(d){
				
			},
			error: function(e){
				
			}
		})
	}
	/*$('.boxgrid.captionfull').hover(function() {
		$(".cover", this).stop().animate({
			top : '160px'
		}, {
			queue : false,
			duration : 160
		});
	}, function() {
		$(".cover", this).stop().animate({
			top : '260px'
		}, {
			queue : false,
			duration : 160
		});
	});*/
	function bindCheckbox(){
		$(":checkbox").on("click", function(){
			if($(this).is(":checked")){
				$(this).val("true");
			}else{
				$(this).val("false");
			}
		})
	}
	
	function bindUploadify(){
		$(":file").uploadify({	
			swf: ctx+"/extends/uploadify/uploadify.swf",
			uploader: ctx+ "/home/upload.do",
			fileTypeExts : "*.png;*.jpg;*.gif",
			fileSizeLimit:"1MB",
			buttonText:'重選熱圖',
			multi           : false,
			uploadLimit: 1,
			removeCompleted: false,
			width:100,
			onSelect : function(file){
				//if();
			},
			onUploadSuccess : function(file, data, response){
				var entity = $.parseJSON(data);
				if(entity){
					//generateImg(entity);
					$("#"+file.id).find(".cancel a").click(function(){
						deleteHotPic(file.id, entity.uploadFileInfoId, true);
					})
					$("#"+file.id).parents("td").find(".hidden-fileInfo").val(entity.uploadFileInfoId);
					var img = $("#"+file.id).parents("tr").find("img");
					var src = img.attr("src");
					var f = src.lastIndexOf("=");
					src = src.substring(0, f);
					img.attr("src", src+"="+entity.uploadFileInfoId);
				}
			},
			onCancel : function(){},
			onUploadError : function(file, errorCode, errorMsg){
				showInfo(errorMsg);
			}
		});
	}
	
	function generateFileInfo(){
		$("tbody tr").each(function(i){
			var fileInfo = $(this).find(".hidden-fileInfo");
			if(fileInfo.val() != ''){
				var deleteFileInfo = $("<a href=\"javascript:void(0)\">X</a>")
				$(this).find(".uploadify-queue").append(
				$("<div class=\"uploadify-queue-item\" id=\"SWFUpload_"+i+"\"></div>").append(					
				$("<div class=\"cancel\">").append(deleteFileInfo)).append(										
				$("<span class=\"fileName\"></span>").text(fileInfo.data("data-fileName")))
				);
				var heatMapId = $(this).find(".hidden-heatMapId").val();
				deleteFileInfo.on("click", function(){
					$(this).parents(".uploadify-queue-item").remove();
					if(heatMapId){
						deleteHeatMapFileInfo(heatMapId);
					}
					deleteHotPic("file-"+fileInfo.val(), fileInfo.val());
				})
			}
		})
	}
	function paginationClick(){
    	   $(".pagination a:not(.disabled):not(.info):not(.current)").on("click",function(){
    		   var pageNo = $(this).attr("data-page");
    		   getHeatMapLists(pageNo);
    	   })
       }  
});